# -*- coding: utf-8 -*-
"""
@Time ： 2021/12/5 21:09
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：app关键字库
"""
import json
import os
import threading
import time

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy


class App:

    def __init__(self):
        # 方便后面关键字点出方法
        self.driver: webdriver.Remote = None
        self.conf = None

    def runappium(self, port='', appium_path=''):
        """
        启动appium服务
        :param port: appium的端口号
        :appium_path port: appium的安装路径
        """
        # 数据驱动时，如果没写参数，给默认值
        if not port:
            port = '4723'

        if not appium_path:
            appium_path = 'E:\software\Appium'

        cmd = r'node %s\resources\app\node_modules\appium\build\lib\main.js --port %s' % (appium_path, port)

        def run_cmd(c):
            """告诉线程要做什么"""
            os.system(c)

        # 定义线程
        th1 = threading.Thread(target=run_cmd, args=(cmd,))

        # # 如果主线程执行完成，那么子线程停止运行
        # th1.setDaemon(True)
        # 运行线程
        th1.start()

    def runapp(self, conf=""):
        """
        启动app，配置用json字符串
        :param conf: app的配置字典
        """
        conf = json.loads(conf)
        self.conf = conf
        self.driver = webdriver.Remote("http://localhost:4723/wd/hub", conf)
        self.driver.implicitly_wait(10)

        # 连接一下设备
        os.system('adb connect %s' % conf.get('devicesname'))

    def __find_ele(self, locator: str = ''):
        # xpath
        if locator.startswith('(') or locator.startswith('/'):
            ele = self.driver.find_element(AppiumBy.XPATH, locator)
        elif locator.__contains__(':id/'):
            # id
            ele = self.driver.find_element(AppiumBy.ID, locator)
        else:
            ele = self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, locator)

        return ele

    def clear(self, locator: str = ""):
        """清空输入框"""
        ele = self.__find_ele(locator)
        ele.clear()

    def input(self, locator: str = '', value=''):
        """输入文本"""
        ele = self.__find_ele(locator)
        ele.send_keys(value)

    def click(self, locator=''):
        """点击"""
        ele = self.__find_ele(locator)
        ele.click()

    def sleep(self,t=''):
        """等待"""
        try:
            t = float(t)
        except Exception as e:
            t = 1

        time.sleep(t)

    def keyevent(self, keycode=''):
        """按键"""
        try:
            keycode = int(keycode)
        except Exception as e:
            keycode = keycode

        self.driver.keyevent(keycode)

    def quit(self):
        """退出连接"""
        self.driver.quit()

    def close(self):
        """关闭appium服务"""
        os.system('taskkill /F /IM node.exe')
